package com.wfs.config;

import org.apache.ibatis.annotations.Mapper;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigurationPackages;
import org.springframework.context.annotation.Bean;

import javax.sql.DataSource;
import java.util.List;

@AutoConfiguration
public class MybatisAutoConfig {
    @Bean
    // 定义一个名为sqlSessionFactoryBean的Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) {
        // 创建一个SqlSessionFactoryBean对象
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        // 设置数据源
        sqlSessionFactoryBean.setDataSource(dataSource);
        // 返回SqlSessionFactoryBean对象
        return sqlSessionFactoryBean;
    }
    @Bean
    // 定义一个MapperScannerConfigurer的Bean
    public MapperScannerConfigurer mapperScannerConfigurer(BeanFactory beanFactory) {
        // 创建一个MapperScannerConfigurer对象
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        // 获取自动配置的包列表
        List<String> basePackages = AutoConfigurationPackages.get(beanFactory);
        // 设置MapperScannerConfigurer的基础包
        mapperScannerConfigurer.setBasePackage(basePackages.get(0));
        // 设置MapperScannerConfigurer的注解类
        mapperScannerConfigurer.setAnnotationClass(Mapper.class);
        // 返回MapperScannerConfigurer对象
        return mapperScannerConfigurer;
    }
}
